package middleware

import (
	"StrayAnimals/pkg/utils"
	"github.com/gin-gonic/gin"
	"strings"
)

// JWTAuthMiddleware 定义 JWT 认证中间件
func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头中获取 Authorization 字段
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
			c.JSON(401, gin.H{
				"code":    411,
				"message": "请求头中缺少 Authorization 字段",
			})
			c.Abort()
			return
		}

		// 提取 Token 去掉前缀 Bearer
		tokenString := strings.TrimPrefix(authHeader, "Bearer ")

		// 解析并验证 Token
		claims, err := utils.ParseToken(tokenString)
		if err != nil {
			c.JSON(401, gin.H{
				"code":    412,
				"message": "Token验证失败；" + err.Error(),
			})
			c.Abort()
			return
		}

		// 将用户id存储到上下文中
		c.Set("id", claims.ID)
		c.Next()
	}
}
